import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import store from '@/store'
import iView from 'iview'
import {
  setToken,
  getToken,
  setTitle,
  localSave,
  localRead
} from '@/libs/util'
import config from '@/config'

const {
  homeName
} = config

// 引入加载菜单
import {
  loadMenu,
  formatMenu
} from '@/libs/router-util'

Vue.use(Router)
// 解决报错
const originalPush = Router.prototype.push
const originalReplace = Router.prototype.replace
// push
Router.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
// replace
Router.prototype.replace = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originalReplace.call(this, location).catch(err => err)
}
const router = new Router({
  routes: [...routes, ...loadMenu()],
  mode: 'history'
})

const LOGIN_PAGE_NAME = 'login'

router.beforeEach((to, from, next) => {
  iView.LoadingBar.start()
  const token = getToken()
  const menu = localRead('route') // 读取路由数据
  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else if (token && menu && menu.length > 0) {
    // 登录了，菜单已存在
    next()// 跳转
  } else {
    store.dispatch('getUserDetailByToken').then(res => {
      // 如果本地不存在路由数据则动态获取
      if (!menu || menu.length === 0) {
        let list = []
        let menuData = res.data.routeVoDataTree.children
        localSave('route', JSON.stringify(menuData))
        // 格式化菜单
        list = formatMenu(menuData)
        // 刷新界面菜单
        store.commit('updateMenuList', list)
        next()
      } else {
        next()
      }
    }).catch(() => {
      setToken('')
      next({
        name: 'login'
      })
    })
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
